package controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import pojo.Collection;
import pojo.User;
import  pojo.Essay;
import service.CollectionServiceI;
import service.EssayServiceI;
import service.MessageServiceI;

@Controller
@RequestMapping("collection")
public class CollectionController {

	/**
	 * @Title: collect   
	 * @Description: 收藏文章
	 * @param: @param request
	 * @param: @return      
	 * @return: String      
	 * @throws
	 */
	@Autowired
	private CollectionServiceI cServiceI;
	@Autowired
	private EssayServiceI essayServiceI;
	@Autowired
	private MessageServiceI messageServiceI;
	@RequestMapping("collect")
	@ResponseBody
	@Transactional(rollbackFor=Exception.class)
	public String collect(HttpServletRequest request,Collection collection) {
		User user=(User) request.getSession().getAttribute("user");
		if(user==null) {
			request.getSession().invalidate();
			return "unlogin";
		}
		int userId=user.getUserId();
		Integer essayId = Integer.valueOf(request.getParameter("essayId")).intValue();
		int j=cServiceI.collectornot(essayId, userId);
		if(j>0) {
			return "alreadycollection";
		}else {
			collection.setEssayId(essayId);
			collection.setUserId(userId);
			int i=cServiceI.collect(collection);
			if(i>0) {
				/*********************进行消息表的插入数据*****************************/
				Integer senduser=userId;
				Essay essay=essayServiceI.FindEssay(essayId);
				Integer receiveuser=essay.getUserId();
				Integer operateflag=3;
				try {
					messageServiceI.MakeMessage(senduser, receiveuser, operateflag, essayId);
				} catch (Exception e) {
					e.printStackTrace();
					return "false";
				}
				/*******************************消息表更新完成******************************************************/
				return "success";
			}else
				return "false";
		}
	}
	
	/**
	 * 
	 * @Title: canclecollect   
	 * @Description: 取消收藏
	 * @param: @param request
	 * @param: @return      
	 * @return: String      
	 * @throws
	 */
	@RequestMapping("canclecollect")
	@ResponseBody
	public String canclecollect(HttpServletRequest request) {
		Integer essayId = Integer.valueOf(request.getParameter("essayId")).intValue();
		User user=(User) request.getSession().getAttribute("user");
		Integer userId=user.getUserId();
		int i=cServiceI.CancleCollection(essayId, userId);
		if(i>0) {
			return "success";
		}else
			return "false";
	}
}
